package com.drd.dt.modular.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.drd.dt.common.Constant;
import com.drd.dt.common.SuccessResultEnum;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.exception.BizExceptionEnum;
import com.drd.dt.exception.BussinessException;
import com.drd.dt.modular.dao.MessageMapper;
import com.drd.dt.modular.dao.UserMoneyMapper;
import com.drd.dt.modular.dto.ActivityDTO;
import com.drd.dt.modular.dto.MessageDTO;
import com.drd.dt.modular.entity.User;
import com.drd.dt.modular.service.MessageService;
import com.drd.dt.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.util.*;

import static com.drd.dt.common.Constant.y_M_d_H_m;

/**
 * Created by 86514 on 2019/3/25.
 */
@Service
@Transactional
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private UserMoneyServiceImpl moneyService;

    @Autowired
    private UserMoneyMapper userMoneyMapper;

    /**
     * 获取消息通知
     **/
    @Override
    public Tip selectMessage(Integer pageNum, Integer type, Integer messageType, Integer user_id, String token_id) throws Exception {
        Page page = new Page(pageNum, Constant.PAGE_SIZE_20);
        //type 类型(1佣金通知 2活动公告 3系统通知)
        //messageType 佣金类型(1普通佣金 2售后扣除 3奖励佣金 4活动佣金)
        List<MessageDTO> data = null;
        if (type == 1 && !StringUtils.isEmpty(user_id)) {
            if (null == messageType) {
                throw new BussinessException(BizExceptionEnum.MESSAGE_COMMISSION_TYPE_EMPTY);
            }
            List<Integer> param = new ArrayList<>();
            Integer mType = 1;
            if (messageType == 1) {//普通佣金
                param.add(1);
                param.add(2);
            } else if (messageType == 2) {//售后扣除
                param.add(4);
                mType = 3;
            } else if (messageType == 3) {//活动奖励
                param.add(3);
                mType = 2;
            }else if (messageType == 4) {//活动佣金
                param.add(5);
            }
            data = messageMapper.selectCommissionMessage(page, param, user_id);
            Integer finalMType = mType;
            data.stream().forEach(t -> {
                if (messageType == 3) {
                    t.setOrder_type(6);//礼包
                }
                Integer origin_id = t.getOrigin_id();
                String fansName = "";
                if (!user_id.equals(origin_id)) {//粉丝消息类型
                    fansName = t.getNick_name();
                }
                String messageText = moneyService.getMessageText(fansName, t.getTime(), t.getCommission(), finalMType);
                if (t.getMessage_type() == 5){//活动佣金
                    t.setTitle("活动奖励");
                    messageText = "恭喜您，在"+t.getTime()+"完成“邀好友拿红包”活动，本次获得"+t.getCommission()+"元活动奖励。";
                }
                t.setContent(messageText);
            });
            messageMapper.updateCommissionMsgStatus(user_id);//更新佣金通知消息读取状态
        } else if (type == 2) {
            data = messageMapper.selectActivityMessage(page);
        } else if (type == 3) {
            //0 全局系统  1，自己注册 2，邀请粉丝成功，有新粉丝注册  3，自己VIP升级 4提现的
            data = messageMapper.selectSystemMessage(page, user_id);
            data.stream().forEach(t -> {
                Integer jump_type = t.getJump_type();
                String nick_name = t.getNick_name();
                Integer mType = 0;
                if (jump_type == 3) {
                    mType = 4;
                    Map map = new HashMap();
                    map.put("id", user_id);
                    User upuser = userMoneyMapper.getByUserId(map);
                    String lv_expire_time = upuser.getLv_expire_time();
                    if (!StringUtils.isEmpty(lv_expire_time)){
                        try {
                            Date parse = y_M_d_H_m.parse(lv_expire_time);
                            t.setTime(y_M_d_H_m.format(parse));//取到会员到期时间
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
                if (jump_type == 1) {
                    nick_name = "";
                }
                if (jump_type != 0 && jump_type != 4){
                    String messageText = moneyService.getMessageText(nick_name, t.getTime(), "", mType);
                    t.setContent(messageText);
                }
            });
            if (!StringUtils.isEmpty(user_id)) {
                messageMapper.updateTXMsgStatus(user_id);//更新提现通知消息读取状态
                messageMapper.updateSYSMsgStatus(user_id);//更新系统通知消息读取状态
            }
        }
        page.setRecords(data);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), page);
    }

    /**
     * 消息中心首页信息
     **/
    @Override
    public Tip simpleInfo(Integer user_id, String token_id) throws Exception {
        List<MessageDTO> info = messageMapper.getMessageInfo(user_id);//活动和系统消息
        final Integer[] commissionCount = {0};
        final Integer[] sysCount = {0};
        if (!StringUtils.isEmpty(user_id)) {
            MessageDTO commission = messageMapper.getCommissionMessageFor1(user_id);//佣金消息
            //获取用户消息读取状态
            List<MessageDTO> status = messageMapper.getReadStatus(user_id);
            status.stream().forEach(t -> {
                Integer jump_type = t.getJump_type();
                if (jump_type == 31 || jump_type == 32) {
                    sysCount[0] += t.getRead_status();
                } else if (jump_type == 1) {
                    commissionCount[0] += t.getRead_status();
                }
            });
            if (null != commission) {
                if (commission.getMessage_type() == 5){//活动佣金
                    commission.setContent("恭喜您，在"+commission.getTime()+"完成“邀好友拿红包”活动，本次获得"+commission.getCommission()+"元活动奖励。");
                }else {
                    commission.setContent("您在" + commission.getTime() + "推广成功,预估佣金:" + commission.getCommission() + "元");
                }
            } else {
                commission = new MessageDTO();
                commission.setJump_type(1);
                commission.setContent(Constant.COMMISSION_MSG);
            }
            info.add(commission);
        }
        info.stream().forEach(t -> {
            //根据type拼接系统消息的内容
            //jump_type：类型(1佣金通知 2活动公告 3系统通知)
            //0 全局系统  1,自己注册 2,邀请粉丝成功，有新粉丝注册  3,自己VIP升级 4提现的
            Integer type = t.getType();
            Integer jump_type = t.getJump_type();
            if (jump_type == 1) {
                if (commissionCount[0] > 0) {
                    t.setRead_status(0);
                } else {
                    t.setRead_status(1);
                }
            } else if (jump_type == 2) {
                t.setRead_status(1);
            } else if (jump_type == 3) {
                if (sysCount[0] > 0) {
                    t.setRead_status(0);
                } else {
                    t.setRead_status(1);
                }
                String nick_name = t.getNick_name();
                Integer mType = 0;
                if (type == 3) {//自己VIP升级
                    mType = 4;
                }
                if (type == 1) {//自己注册
                    nick_name = "";
                }
                if (type != 0 && type != 4) {
                    String messageText = moneyService.getMessageText(nick_name, t.getTime(), "", mType);
                    t.setContent(messageText);
                }
            }
        });
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), info);
    }
}
